import sys
import glob
import os

samplePre = sys.argv[1] # "%s/%s*" % (workdir,samplePre)
NewPre = sys.argv[2]
workdir = sys.argv[3]
start = int(sys.argv[4])

#finish in 2020.4.24
#rename fq to run cellranger.inside fqstq prename is NewPre
#dirname like: P1-Tumor-CDNA-library_1/NewPre_S1_L001_R1_001.fastq.gz
#change x_combine.R1.fastq to x_S1_L001_R1_001.fastq.gz

path = "%s/%s*" % (workdir,samplePre)

temp = glob.glob(path)
temp.sort()

c = start
for i in temp:
    thisSampleDir = os.path.basename(i)

    #fastq rename
    fq1path = "%s/*_combined_R1.fastq.gz" % (i)
    fq1 = glob.glob(fq1path)
    
    fq2path = "%s/*_combined_R2.fastq.gz" % (i)
    fq2 = glob.glob(fq2path)

    if len(fq1) == 1 and len(fq2) == 1:
        nfq1 = "%s/%s/%s_S%s_L001_R1_001.fastq.gz" % (workdir,thisSampleDir,NewPre,c)
        nfq2 = "%s/%s/%s_S%s_L001_R2_001.fastq.gz" % (workdir,thisSampleDir,NewPre,c)
        cmd = "mv %s %s" % (fq1[0],nfq1)
        print(cmd)
        cmd = "mv %s %s" % (fq2[0],nfq2)
        print(cmd)

    #rename thisSampleDir
    cmd = "mv %s %s/%s_%s" % (i,workdir,NewPre,c)
    print(cmd)

    c += 1
